package com.zbf.user.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zbf.auth.mapper.UserDao;
import com.zbf.common.entity.ResponseResult;
import com.zbf.common.entity.UserEntity;
import com.zbf.common.exception.AllRedisKeyEnum;
import com.zbf.common.exception.AllStatusEnum;
import com.zbf.common.utils.*;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 作者: Mr.Wu
 * 日期: 2020/9/12
 * 描述: 这是用来注册时所用的类
 */
@RestController
@RequestMapping("userReg")
public class RegistController {

    @Autowired
    UserDao userDao;
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Value("${active.path}")
    private  String activePath;

    /*md5加密的盐*/
    private final static String salt = "weh";
    /*用于比较的中间替换*/
    private static String center = "";


    /**
     * 用来比对前端输入验证码是否和获取到的一致
     * @param code
     * @return
     */
    @RequestMapping("identical")
    public boolean yzsame(String code){
        System.out.println("传入的验证码"+code);
        String s = redisTemplate.opsForValue().get("code");
        System.out.println("获取到的验证码***"+s);
        if (s.equals(code)){
            System.out.println("一致可通过");
            redisTemplate.delete("code");
            return true;
        }
          return false;
    }


    /**
     * 用来将前台数据存入数据库，并向邮箱发送激活邮件
     * @param userEntity
     * @return
     */
    @RequestMapping("toRegister")
    public ResponseResult regist(@RequestBody UserEntity userEntity){
        System.out.println("进入注册方法,接收到的对象"+userEntity);
        ResponseResult responseResult = ResponseResult.getResponseResult();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                MailQQUtils.sendMessage(userEntity.getEmail(),"点击前往激活","云翔科技",
                        getActivePath(activePath,2*60*1000L,userEntity.getLoginName()));
            }
        });
        thread.start();
        userEntity.setActiveStatus(0);
        boolean b = userDao.insertUser(userEntity);
        if (b){
            responseResult.setCode(AllStatusEnum.REGIST_SUCCESS.getCode());
            responseResult.setMsg(AllStatusEnum.REGIST_SUCCESS.getMsg());
            return responseResult;
        }else {
            responseResult.setCode(AllStatusEnum.REGIST_FAIL.getCode());
            responseResult.setMsg(AllStatusEnum.REGIST_FAIL.getMsg());
            return responseResult;
        }

    }

   /* @RequestMapping("toActive")
    public boolean toactive(String account) throws Exception {


        return true;
    }*/

    /**
     * 激活用户
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("activeUser")
    public void activeUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("进入激活用户方法");
        //获取激活的串
        String actived = request.getParameter("actived");
        String loginName = request.getParameter("loginName");
        System.out.println("获取actived");
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();

        //设置响应头的格式
        response.setContentType("text/html;charset=UTF-8");
        //解析激活串
        try{
            JSONObject jsonObject = JwtUtilsForOther.decodeJwtTocken(actived);

            JSONObject info = JSON.parseObject(jsonObject.getString("info"));

            //获取存储的激活码
            String code = redisTemplate.opsForValue().get(AllRedisKeyEnum.ACTIVIVE_KEY.getKey() +"_"+ info.get("loginName"));

            //激活成功后跳转到激活成功页面
            //在激活成功的页面可以跳转到登录界面，进行登录
            //如果激活码正确
            if(info.get("code").equals(code)){
                System.out.println("激活码正确进入activeOk页面");
                stringObjectHashMap.put("loginPath","http://localhost:8080/");
                FreemarkerUtils.getStaticHtml(RestController.class,"/template/","activeOk.html",stringObjectHashMap,response.getWriter());
            }else{
                System.out.println("激活码正确进入activeError页面");
                stringObjectHashMap.put("newActiveLink","http://10.162.6.66:10000/user/userReg/getNewActiveLink?loginName="+loginName);
                FreemarkerUtils.getStaticHtml(RestController.class,"/template/","activeError.html",stringObjectHashMap,response.getWriter());
            }

        }catch (ExpiredJwtException e){
            System.out.println("过期重新发送");
            HashMap<String, Object> newData = new HashMap<>();
            //String loginName = request.getParameter("loginName");
            newData.put("newActiveLink","http://10.162.6.66:10000/user/userReg/getNewActiveLink?loginName="+loginName);
            FreemarkerUtils.getStaticHtml(RestController.class,"/template/","activeError.html",newData,response.getWriter());

        }

    }


    /**
     * 激活信息,timeOut
     * @param baseActivePath   激活的基本路劲
     * @param timeOut   有效期
     * @param loginName 登录名
     * @return
     */
    public  String getActivePath(String baseActivePath, long timeOut, String loginName){
        //激活信息
        String code= UID.getUUID16();
        //放入redis 中
        String key=AllRedisKeyEnum.ACTIVIVE_KEY.getKey()+"_"+loginName;
        redisTemplate.opsForValue().set(key,code);
        //设置redis的key过期时间
        redisTemplate.expire(key,timeOut, TimeUnit.MILLISECONDS);
        //生成激活的链接地址
        StringBuffer stringBuffer=new StringBuffer(activePath);
        stringBuffer.append("?");
        stringBuffer.append("loginName="+loginName);
        stringBuffer.append("&");
        stringBuffer.append("actived=");
        Map<String,String> map=new HashMap<>();
        map.put("loginName",loginName);
        map.put("code",code);
        stringBuffer.append(JwtUtilsForOther.generateToken(JSON.toJSONString(map),timeOut));
        String path=stringBuffer.toString();
        stringBuffer=null;
        return path;
    }

    @RequestMapping("getNewActiveLink")
    public void getNewActiveLink(HttpServletRequest request,HttpServletResponse response) throws Exception {

        HashMap<String, Object> stringObjectHashMap = new HashMap<>();

        //设置响应头的格式
        response.setContentType("text/html;charset=UTF-8");

        //如果jwt过期，重新的发激活邮件
        String loginName = request.getParameter("loginName");
        //根据loginName获取用户信息
        //3、扣扣邮箱发送激活邮件
        MailQQUtils.sendMessage("772617928@qq.com","","云翔科技",getActivePath(activePath,2*60*1000L,loginName));

        FreemarkerUtils.getStaticHtml(RestController.class,"/template/","sendOK.html",stringObjectHashMap,response.getWriter());
    }


    @RequestMapping("updatePwd")
    public boolean updatePwd(String pwd,String tel){
        System.out.println("进入修改方法");
        boolean b = userDao.updatePwd(pwd, tel);
        System.out.println("修改结果"+b);
        return b;
    }
}
